package com.wwdx.wechat.handler;

import com.google.common.collect.Lists;
import com.wwdx.model.WwdxWeixinUserModel;
import com.wwdx.service.impl.BaseWxService;
import com.wwdx.utils.ConstantHolder;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author liguoliang
 */
public abstract class AbstractSubscribeHandler extends AbstractHandler {

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        BaseWxService service = (BaseWxService) wxMpService;
        String openId = wxMessage.getFromUser();
        logger.info("新关注用户 OPENID: {}" , openId);
        //获取微信用户基本信息
        WxMpUser wxMpUser = service.getUserService().userInfo(openId);
        sendKefuMessage(wxMpUser,service);
        setOperations.add(ConstantHolder.USER_CONCERN_TOTAL_COUNT, openId);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String timeKey = String.format(ConstantHolder.USER_CONCERN_TIME, openId);
            valueOperations.set(timeKey,format.parse(format.format(new Date())).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //红包领取
        Boolean aBoolean = hashOperations.hasKey(ConstantHolder.USER_RED_PACKET_COUNT, wxMpUser.getUnionId());
        if (!aBoolean)hashOperations.put(ConstantHolder.USER_RED_PACKET_COUNT, wxMpUser.getUnionId(), "1");
        WwdxWeixinUserModel model = WwdxWeixinUserModel.builder().gmtCreated(new Date()).appid("wx91e8b20a8fce5f03").unionid(wxMpUser.getUnionId())
                .gmtModified(new Date()).openid(openId).nickname(wxMpUser.getNickname()).build();
        if (wwdxWeixinUserService.getByOpenId(openId)==null) wwdxWeixinUserService.save(model);
        return null;
    }
    private void sendKefuMessage(WxMpUser wxMpUser,BaseWxService service) throws WxErrorException {
        WxMpKefuMessage message = new WxMpKefuMessage();
        //第一条消息
        String content = "嗨，我是蜜读君，很高兴认识你~\n\n" +
                "听说优秀的人才会关注“蜜读听书”，原来你也如此优秀！\n\n" +
                "<a href =\""+wechatUrl+"dingyu.html?logoId=1&openId="+wxMpUser.getOpenId()+"\">新用户福利汇总</a>\n";
        message.setMsgType(WxConsts.KefuMsgType.TEXT);
        message.setToUser(wxMpUser.getOpenId());
        message.setContent(content);
        service.getKefuService().sendKefuMessage(message);
        //第二条消息
        WxMpKefuMessage message2 = new WxMpKefuMessage();
        String content2 = "1⃣<a href =\""+wechatUrl+"dingyu.html?logoId=2&openId="+wxMpUser.getOpenId()+"\">由内而外，打造100%优雅女神</a>\n\n" +
                "1⃣<a href =\""+wechatUrl+"dingyu.html?logoId=3&openId="+wxMpUser.getOpenId()+"\">找对方法，人人都能“速成”职场精英</a>\n\n" +
                "3⃣<a href =\""+wechatUrl+"dingyu.html?logoId=4&openId="+wxMpUser.getOpenId()+"\">每天1元，500本好书无限畅听</a>\n";
        message2.setMsgType(WxConsts.KefuMsgType.TEXT);
        message2.setToUser(wxMpUser.getOpenId());
        message2.setContent(content2);
        service.getKefuService().sendKefuMessage(message2);
        //第三条消息
        WxMpKefuMessage message3 = new WxMpKefuMessage();
        WxMpKefuMessage.WxArticle article = new WxMpKefuMessage.WxArticle();
        String url="http://img.readerday.com/pullxin/hongbao.jpg";
        article.setPicUrl(url);
        article.setDescription("@"+wxMpUser.getNickname()+"，点击领取35元新人红包，28位微信好友已领取");
        article.setUrl(wechatUrl+"dingyu.html?logoId=5&openId="+wxMpUser.getOpenId());
        List<WxMpKefuMessage.WxArticle> articles = Lists.newArrayList(article);
        message3.setMsgType(WxConsts.XmlMsgType.NEWS);
        message3.setToUser(wxMpUser.getOpenId());
        message3.setArticles(articles);
        miDuWxService.getKefuService().sendKefuMessage(message3);
    }
}
//package com.wwdx.wechat.handler;
//
//import com.google.common.collect.Lists;
//import com.wwdx.model.WwdxWeixinUserModel;
//import com.wwdx.model.dto.BaseActivityDTO;
//import com.wwdx.service.impl.BaseWxService;
//import com.wwdx.utils.ConstantHolder;
//import me.chanjar.weixin.common.api.WxConsts;
//import me.chanjar.weixin.common.error.WxErrorException;
//import me.chanjar.weixin.common.session.WxSessionManager;
//import me.chanjar.weixin.mp.api.WxMpService;
//import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
//import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
//import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
//import me.chanjar.weixin.mp.bean.result.WxMpUser;
//import org.apache.commons.lang3.StringUtils;
//import org.joda.time.LocalDate;
//
//import java.util.Date;
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.TimeUnit;
//
///**
// * @author liguoliang
// */
//public abstract class AbstractSubscribeHandler extends AbstractHandler {
//
//    @Override
//    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
//        BaseWxService service = (BaseWxService) wxMpService;
//        String openId = wxMessage.getFromUser();
//        logger.info("新关注用户 OPENID: {}" , openId);
//        //获取微信用户基本信息
//        WxMpUser wxMpUser = service.getUserService().userInfo(openId);
//        Integer sex = wxMpUser.getSex();
//        Long subscribeTime = wxMpUser.getSubscribeTime();
//        String city = wxMpUser.getCity(),country = wxMpUser.getCountry(),province = wxMpUser.getProvince(),
//                unionId = wxMpUser.getUnionId(),appId = service.getWxMpConfigStorage().getAppId(),
//                nickname = wxMpUser.getNickname(),headImgUrl = wxMpUser.getHeadImgUrl();
//        WwdxWeixinUserModel wwdxWeixinUserModel = wwdxWeixinUserService.getByOpenId(openId);
//        if (wwdxWeixinUserModel == null){
//            wwdxWeixinUserModel = WwdxWeixinUserModel.builder()
//                    .openid(openId).appid(appId).unionid(unionId).nickname(nickname).sex(sex).headimgurl(headImgUrl)
//                    .city(city).country(country).province(province).language(wxMpUser.getLanguage()).subscribe(Boolean.TRUE)
//                    .subscribeTime(subscribeTime).gmtCreated(new Date()).gmtModified(new Date()).build();
//            wwdxWeixinUserService.save(wwdxWeixinUserModel);
//        }
//        //订阅页新关注用户默认订阅
//        String eventKey = wxMessage.getEventKey();
//        if (StringUtils.isNotBlank(eventKey)){
//            //渠道二维码票据
//            String channelSources = StringUtils.substringAfter(eventKey, "_");
//            String subscribe = "subscribe";
//            if (subscribe.equalsIgnoreCase(channelSources)){
//                //新增用户
//                String date = new LocalDate().toString();
//                String subscribeNewKey = String.format(ConstantHolder.USER_SUBSCRIBE_NEW_SET, date);
//                setOperations.add(subscribeNewKey,unionId);
//                redisTemplate.expire(subscribeNewKey,30 * 60 * 60 , TimeUnit.SECONDS);
//                setOperations.add(ConstantHolder.USER_SUBSCRIBE_TOTAL_SET, unionId);
//            }
//        }
//        //发送客服消息
//        //this.sendKefuMessage(openId,service);
//        //赠一得一未关注通知
//        taskExecutor.execute(()->{
//            Boolean member = hashOperations.hasKey(ConstantHolder.GIVEONE_UNIONID_MAP, unionId);
//            if (member){
//                BaseActivityDTO.GiveOneBusinessDTO dto = (BaseActivityDTO.GiveOneBusinessDTO) hashOperations.get(ConstantHolder.GIVEONE_UNIONID_MAP, unionId);
//                Long bookid = dto.getBookid();
//                //保存赠一得一订单
//                if (dto.getBookFlag().equalsIgnoreCase(bookid.toString())){
//                    payService.executeGiveoneOrder(dto);
//                }
//                hashOperations.delete(ConstantHolder.GIVEONE_UNIONID_MAP,unionId);
//            }
//        });
//        return null;
//    }
//
//    private void sendKefuMessage(String openid,BaseWxService service) throws WxErrorException{
//        WxMpKefuMessage.WxArticle article = new WxMpKefuMessage.WxArticle();
//        WxMpUser wxMpUser = service.getUserService().userInfo(openid);
//        String url="http://mmbiz.qpic.cn/mmbiz_png/G8V8d8SnNEPo2icxhdPzAAB1992zYkv26HvpPYtKZ0RXFMo0oS0MtgibcVGlz9a6QWaEtMtntssicIBeSu1U6N9VA/0?wx_fmt=png";
//        article.setPicUrl(url);
//        article.setDescription("@"+wxMpUser.getNickname()+"！欢迎来到蜜读听书，以帮助100多万听书用户奉献知识精华，点击免费领书。");
//        article.setUrl(wechatUrl+"auth.html");
//        List<WxMpKefuMessage.WxArticle> articles = Lists.newArrayList(article);
//        WxMpKefuMessage message = new WxMpKefuMessage();
//        message.setToUser(openid);
//        message.setMsgType(WxConsts.XmlMsgType.NEWS);
//        message.setArticles(articles);
//        service.getKefuService().sendKefuMessage(message);
//    }
//}